package com.example.jucdemo.api;

import com.example.jucdemo.status.DoorStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class DoorController {

    private DoorStatus doorStatus = new DoorStatus();

    @GetMapping("/view-door")
    public Map<String,Object> viewDoorStatus(){
        synchronized (doorStatus){
            while (!doorStatus.isOpened()) {
                try {
                    doorStatus.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Map<String,Object> map = new HashMap<>();
            map.put("success", true);
            return map;
        }
    }

    @GetMapping("/open-door")
    public Map<String,Object> openDoor(){

        //打开阀门是一个耗时操作,另起一个线程单独处理
        new Thread(()->{
            try {//模拟一个耗时操作
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            doorStatus.setOpened(true);
            synchronized (doorStatus){
                doorStatus.notify();
            }


        }).start();


        Map<String,Object> map = new HashMap<>();
        map.put("success", true);
        return map;

    }
}
